package com.heima.kafka.sample;

import org.apache.kafka.clients.producer.*;

import java.util.Properties;
import java.util.concurrent.ExecutionException;

/**
 * 消息的生产者
 */
public class ProducesQuickStart {

    public static void main(String[] args) {

        //kafka配置
        Properties properties = new Properties();
        //链接地址
        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG,"192.168.200.130:9092");
        //key和vlaue的序列化
        properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.StringSerializer");
        properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.StringSerializer");
        //消息确认
        properties.put(ProducerConfig.ACKS_CONFIG,"all");
        //重试次数
        properties.put(ProducerConfig.RETRIES_CONFIG,"10");

        //创建消息的生产者对象
        KafkaProducer<String,String> kafkaProducer = new KafkaProducer<String,String>(properties);

        for (int i = 0; i < 10; i++) {
            //封装消息
            ProducerRecord<String,String> record = new ProducerRecord<String,String>("stream-input-topic","hello kafka hello");
            kafkaProducer.send(record);
        }

        //发送消息
        //同步发送消息
        /*RecordMetadata recordMetadata = null;
        try {
            recordMetadata = kafkaProducer.send(record).get();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        System.out.println(recordMetadata.partition());*/
        /*kafkaProducer.send(record, new Callback() {
            @Override
            public void onCompletion(RecordMetadata recordMetadata, Exception e) {
                if(e != null){
                    System.out.println("消息发送失败");
                }
                System.out.println(recordMetadata.partition());
            }
        });*/


        //关闭消息通道，不然消息发送不成功
        kafkaProducer.close();
    }
}
